package 文件IO.文件搜索案例二_查内容匹配;

import java.io.*;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        //1.必要内容信息
        Scanner sc = new Scanner(System.in);
        System.out.println("输入搜索路径 :");
        String path = sc.next();
        System.out.println("输入查询词");
        String searchWord = sc.next();

        //2.判断合法
        File rootFile = new File(path);
        if(!rootFile.isDirectory()){
            System.out.println("您输入的不合法" + path);
            return;
        }

        //3.递归查找
        search(rootFile,searchWord);
    }
    public static void search(File rootFile , String searchWord){
        File[] files = rootFile.listFiles();
        if(files == null){
            return;
        }
        for(File f : files){
            if(f.isFile()){
                //文件内容搜索
                matchWord(f,searchWord);
            }else if(f.isDirectory()){
                //文件递归
                search(f,searchWord);
            }
        }
    }

    private static void matchWord(File f, String searchWord) {
        //负责文件读取判定
        try(Reader reader = new FileReader(f)){
            //把结果放到 StringBuilder
            StringBuilder stringBuilder = new StringBuilder();
            while(true){
                int c = reader.read();
                if( c == -1){
                    break;
                }
                stringBuilder.append((char)c);
            }
            if(stringBuilder.indexOf(searchWord) >= 0){
                System.out.println("找到了:"+ f.getAbsoluteFile());
            }
        }  catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
